package com.googlecode.connectlet.tsa;

import java.io.IOException;

import com.googlecode.connectlet.util.secure.CertKey;
import com.googlecode.connectlet.util.secure.CertMap;

import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;

public class TimeStampResp {
	private PKCS7 token;

	public TimeStampResp(PKCS7 token) {
		this.token = token;
	}

	public TimeStampResp(TstInfo tstInfo, CertKey... certKeys) throws IOException {
		this(P7S.sign(ContentInfo.TIMESTAMP_TOKEN_INFO_OID, tstInfo.getEncoded(), certKeys));
	}

	public TimeStampResp(byte[] encoded) throws IOException {
		DerValue[] ders = new DerInputStream(encoded).getSequence(0);
		if (ders.length < 2) {
			throw new IOException("Invalid DER Format");
		}
		token = new PKCS7(ders[1].toByteArray());
	}

	public PKCS7 getToken() {
		return token;
	}

	public boolean verify(CertMap certMap) throws Exception {
		return P7S.verify(token, certMap);
	}

	public byte[] getEncoded() throws IOException {
		DerOutputStream status = new DerOutputStream();
		status.putInteger(0);
		DerOutputStream tsResp = new DerOutputStream();
		tsResp.write(DerValue.tag_Sequence, status);
		token.encodeSignedData(tsResp);
		DerOutputStream dos = new DerOutputStream();
		dos.write(DerValue.tag_Sequence, tsResp);
		return dos.toByteArray();
	}
}